package cn.touna.jss.modules.third.baidu;

import cn.touna.risk.api.contraints.facet.First;
import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.properties.disconf.BaiduProperties;
import cn.touna.jss.common.util.HttpUtil;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.third.baidu.entity.BaiduRequestEntity;
import cn.touna.risk.api.domain.Response;
import com.alibaba.fastjson.JSONObject;
import com.touna.loan.log.service.TracerContextUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * <P>百度黑名单</P>
 * User: tianhuaxing
 * Date: 2017/7/31
 * Time: 11:05
 */
@Service
public class BaiDuService {

    private static final Logger logger = LogManager.getLogger(BaiDuService.class);

    @Resource(name = "httpsRestTemplate")
    private RestTemplate restTemplate;

    @Autowired
    private BaiduProperties baiduProperties;

   /* @ApiMapping("baidu.getBlackList2")
    public Response<String> getBlackList(BaiduRequestEntity request) {
        request.setRequestId(TracerContextUtil.getTraceId());
        Response response = ValidUtil.valid(request);
        if (response == null) {
            JSONObject map = new JSONObject();
            map.put("reqId", request.getRequestId());
            map.put("sign", "");
            map.put("timestamp", String.valueOf(System.currentTimeMillis()));
            map.put("prcid", request.getIdCard());
            map.put("phoneNumber", request.getMobile());
            map.put("sourceName", baiduProperties.getSourceName());
            map.put("signType", "1");
            map.put("name", request.getName());
            map.put("eventType", baiduProperties.getEventType());

            String sign = DigestUtils.md5Hex(JSON.toJSONString(map).concat("verificationCode=").concat(baiduProperties.getVerificationCode()));
            map.put("sign", sign);
            try {
                String res = HttpUtil.postJson(baiduProperties.getCreditApi(), map);
                if (StringUtils.isEmpty(res)) {
                    return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR);
                }
                JSONObject jRes = JSONObject.parseObject(res);
                if ("0".equals(jRes.getString("retCode"))) {
                    return ResponseFactory.success(res);
                } else {
                    return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR, jRes.getString("retMsg"));
                }
            } catch (Exception e) {
                logger.error("调用百度黑名单报错，", e);
                return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getMessage());
            }
        }
        return response;
    }*/

    @ApiMapping(value = "baidu.creditScore",desc = "百度.评分")
    public Response creditScore(BaiduRequestEntity request) {
        Response response = new Response();

        Map<String,String> map = new HashMap<>();

        String reqid = TracerContextUtil.getTraceId();
        String datetime = String.valueOf(System.currentTimeMillis());
        map.put("sp_no",baiduProperties.getSp_no());
        map.put("service_id","1007");
        map.put("reqid",reqid);
        map.put("name",request.getName());
        map.put("identity",request.getIdCard());
        map.put("phone",request.getMobile());
        map.put("datetime",datetime);
        map.put("sign_type","1");
        map.put("models","general_preA");



        String signSrc = "datetime=%s&identity=%s&models=%s&name=%s&phone=%s&reqid=%s&service_id=%s&sign_type=%s&sp_no=%s&key=%s";
        String sign = String.format(signSrc,datetime,request.getIdCard(),"general_preA",
                request.getName(),request.getMobile(),reqid,"1007","1",baiduProperties.getSp_no(),
                baiduProperties.getKey());
        try {
            sign = DigestUtils.md5Hex(sign);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        map.put("sign",sign);
        try {
            String res = null;
            res = HttpUtil.get(baiduProperties.getRiskApiUrl(),map);
            logger.info("baidu.creditScore result:{} ",res);
            JSONObject resObj = JSONObject.parseObject(res);
            if(resObj.getInteger("retCode") == 0){
                return response.success(res);
            }else{
                String msg = resObj.getString("retMsg");
                return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR,msg,resObj);
            }
        } catch (Exception e) {
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR,e.getMessage());
        }
    }



    @ApiMapping(value = "baidu.multiInfo",desc = "百度.多头信息查询")
    public Response multiInfo(BaiduRequestEntity request) {
        Response response = new Response();
        Response validResponse = ValidUtil.valid(request, First.class);
        if (validResponse != null)
            return validResponse;
        Map<String,String> map = new HashMap<>();

        String reqid = TracerContextUtil.getTraceId();
        String datetime = String.valueOf(System.currentTimeMillis());
        map.put("sp_no",baiduProperties.getSp_no());
        map.put("service_id","1002");
        map.put("reqid",reqid);
        map.put("name",request.getName());
        map.put("identity",request.getIdCard());
        map.put("phone",request.getMobile());
        map.put("datetime",datetime);
        map.put("sign_type","1");
//        map.put("models","general_preA");

        String signSrc = "datetime=%s&identity=%s&name=%s&phone=%s&reqid=%s&service_id=%s&sign_type=%s&sp_no=%s&key=%s";
        String sign = String.format(signSrc,datetime,request.getIdCard(),
                request.getName(),request.getMobile(),reqid,"1002","1",baiduProperties.getSp_no(),
                baiduProperties.getKey());
        try {
            sign = DigestUtils.md5Hex(sign);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        map.put("sign",sign);
        try {
            String res = HttpUtil.get(baiduProperties.getRiskApiUrl(),map);
            logger.info("baidu.creditScore result:{} ",res);
            JSONObject resObj = JSONObject.parseObject(res);
            if(resObj.getInteger("retCode") == 0){
                return response.success(resObj);
            }else{
                String msg = resObj.getString("retMsg");
                return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR,msg,resObj);
            }
        } catch (Exception e) {
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR,e.getMessage());
        }
    }




    @ApiMapping(value = "baidu.getBlackList", desc = "百度.黑名单")
    public Response<String> getBlackList(BaiduRequestEntity request) {
        Response response = new Response();
        Response validResponse = ValidUtil.valid(request, First.class);
        if (validResponse != null)
            return validResponse;

        Map<String,String> map = new HashMap<>();

        String reqid = TracerContextUtil.getTraceId();
        String datetime = String.valueOf(System.currentTimeMillis());
        map.put("sp_no",baiduProperties.getSp_no());
        map.put("service_id",baiduProperties.getService_id());
        map.put("reqid",reqid);
        map.put("name",request.getName());
        map.put("identity",request.getIdCard());
        map.put("phone",request.getMobile());
        map.put("datetime",datetime);
        map.put("sign_type","1");

        String signSrc = "datetime=%s&identity=%s&name=%s&phone=%s&reqid=%s&service_id=%s&sign_type=%s&sp_no=%s&key=%s";
        String sign = String.format(signSrc,datetime,request.getIdCard(),
                request.getName(),request.getMobile(),reqid,baiduProperties.getService_id(),"1",baiduProperties.getSp_no(),
                baiduProperties.getKey());
        try {
            sign = DigestUtils.md5Hex(sign);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        map.put("sign",sign);
        try {
            String res = null;
            res = HttpUtil.get(baiduProperties.getRiskApiUrl(),map);
            System.out.println(res);
            JSONObject resObj = JSONObject.parseObject(res);
            if(resObj.getInteger("retCode") == 0){
                return ResponseFactory.success(res);
            }else{
                 String msg = resObj.getString("retMsg");
                 return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR,msg,resObj);
            }
        } catch (Exception e) {
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR,e.getMessage());
        }
    }

    private String post(String urlStr, String content) throws Exception {
        HttpURLConnection conn = null;
        BufferedWriter bw = null;
        BufferedReader br = null;
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();

            bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
            bw.write(content);
            bw.flush();
            bw.close();
            br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            System.out.println(sb.toString());
            br.close();
            bw.close();
            conn.disconnect();
            return sb.toString();
        } catch (Exception e) {
            logger.error("", e);
            throw e;
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null)
                conn.disconnect();
        }
    }
}
